package org.beetl.sql.ext;

import org.beetl.sql.core.InterceptorContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;

/**
 * SQL输出到日志
 * Created by chenss on 2019/6/13.
 */
public class MyDebugInterceptor extends DebugInterceptor {

    static Logger logger = LoggerFactory.getLogger(MyDebugInterceptor.class);

    @Override
    protected void println(String str) {
//        String lineSeparator = System.getProperty("line.separator", "\n");
        String lineSeparator ="";
        logger.info(lineSeparator+str);
    }

   @Override
    public void before(InterceptorContext ctx) {
        String sqlId = ctx.getSqlId();
        if (this.isDebugEanble(sqlId)) {
            ctx.put("debug.time", System.currentTimeMillis());
        }
        if (this.isSimple(sqlId)) {
            return;
        }
        StringBuilder sb = new StringBuilder();
//        String lineSeparator = System.getProperty("line.separator", "\n");
        String lineSeparator ="";
        sb.append(" [").append(this.getSqlId(formatSql(sqlId))).append("] ").append(lineSeparator)
                .append(" DebugSQL：" + formatSql(ctx.getSql()) + lineSeparator)
                .append(" 参数：" + formatParas(ctx.getParas())).append(lineSeparator);
        RuntimeException ex = new RuntimeException();
        StackTraceElement[] traces = ex.getStackTrace();
        int index = lookBusinessCodeInTrace(traces);
        StackTraceElement bussinessCode = traces[index];
        String className = bussinessCode.getClassName();
        String mehodName = bussinessCode.getMethodName();
        int line = bussinessCode.getLineNumber();
        sb.append(" 位置：" + className + "." + mehodName + "(" + bussinessCode.getFileName() + ":" + line + ")"
                + lineSeparator);

        ctx.put("logs", sb);
    }

    @Override
    protected int lookBusinessCodeInTrace(StackTraceElement[] traces) {
        for (int j = 6; j < traces.length - 1; j++) {
            if(traces[j].getClassName().startsWith("com.andnnl")){
                return j;
            }
        }
        return super.lookBusinessCodeInTrace(traces);
    }

    @Override
    public void after(InterceptorContext ctx) {
        String sqlId = ctx.getSqlId();
        if (this.isSimple(sqlId)) {
            this.simpleOut(ctx);
            return;
        }
        long time = System.currentTimeMillis();
        long start = (Long) ctx.get("debug.time");
//        String lineSeparator = System.getProperty("line.separator", "\n");
        String lineSeparator ="";
        StringBuilder sb =new StringBuilder();
//        sb.append(" times：\t " + (time - start) + "ms").append(lineSeparator);
        sb.insert(0,"times：\t" + (time - start) + "ms");
        if (ctx.isUpdate()) {
            sb.append(" 更新：[");
            if (ctx.getResult().getClass().isArray()) {
                int[] ret = (int[]) ctx.getResult();
                for (int i = 0; i < ret.length; i++) {
                    if (i > 0)
                        sb.append(",");
                    sb.append(ret[i]);
                }
            } else {
                sb.append(ctx.getResult());
            }
            sb.append("]").append(lineSeparator);
        } else {
            if (ctx.getResult() instanceof Collection) {
                sb.append(" 结果：[").append(((Collection) ctx.getResult()).size()).append("]").append(lineSeparator);
            } else {
                sb.append(" 结果：[").append(ctx.getResult()).append("]").append(lineSeparator);
            }

        }
//        sb.append(" DebugSQL [").append(this.getSqlId(formatSql(ctx.getSqlId()))).append("] ━━━")
//                .append(lineSeparator);

        println(sb.toString()+(StringBuilder) ctx.get("logs"));

    }
}
